package cn.edu.zafu.bigdata.Wym;

import java.io.*;
import java.util.Scanner;

public class Wym_WriteAndReadTextFile {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        //Scanner是java.util包中的一个类，可以从不同输入源（如文件、输入流、字符串等）中解析基本类型和字符串

        System.out.println("Enter your student ID:");
        String studentId = scanner.nextLine();
        String fileName = "files/" + studentId + ".txt";

        System.out.println("Enter the text you want to save:");
        String content = scanner.nextLine();

        writeToFile(fileName, content);
        System.out.println("Content written to file " + fileName);

        System.out.println("Reading content from file " + fileName + ":");
        String fileContent = readFromFile(fileName);
        System.out.println(fileContent);
    }

    private static void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String readFromFile(String fileName) {
        StringBuilder contentBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                contentBuilder.append(line).append(System.lineSeparator());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return contentBuilder.toString();
    }
}